#if DEBUG_LEVEL > 0
#include <iostream>
using std::cout;
using std::endl;
#endif

#include "GameManager.h"

GameManager::GameManager(Player** playerGroup) {
    for (int i = 0; i < NUM_PLAYERS; i++) {
        players[i] = playerGroup[i];
        players[i]->setGame(&gameState);
    }
}

void GameManager::run() {
    for (int i = 0; i < NUM_PLAYERS; i++) {
        players[i]->receiveDeal(gameState.deal(i));
        matchStatistics.initScore[i] = players[i]->revealHand().Value();
    }
    bool gameOver = false;
    int knockingPlayer = -1;
    matchStatistics.rounds = 0;
    while (!gameOver) {
        matchStatistics.rounds++;
        for (int i = 0; i < NUM_PLAYERS; i++) {
            if (i != knockingPlayer) {
                const Move& move = players[i]->decideMove();
#if DEBUG_LEVEL > 1
                cout << "Player " << i << " has "
                     << players[i]->revealHand().Initials() << " for "
                     << players[i]->revealHand().Value() << ".\n";
                cout.flush();
#endif
//                 for (int j = 0; j < NUM_PLAYERS; j++) {
//                     if (j != i) {
//                         players[j]->opponentMove(i, move);
//                     }
//                 }
                if (players[i]->revealHand().Value()==31) {
#if DEBUG_LEVEL > 0
                  cout << "Player " << i << " got 31! Game over.\n";
                  cout.flush();
#endif
                  gameOver = true;
                  break;
                }
                if (knockingPlayer < 0 && gameState.isLastRound()) {
#if DEBUG_LEVEL > 0
                  cout << "Player " << i << " knocked.\n";
                  cout.flush();
#endif
                  knockingPlayer = i;
                }
            }
            else {
                gameOver = true;
                break;
            }
        }
    }
    int minScore = 32;
    for (int i = 0; i < NUM_PLAYERS; i++) {
        matchStatistics.score[i] = players[i]->revealHand().Value();
        if (matchStatistics.score[i] == minScore) {
            if (knockingPlayer == i) {
                matchStatistics.loser = i;
            }
        }
        else if (matchStatistics.score[i] < minScore) {
            matchStatistics.loser = i;
            minScore = matchStatistics.score[i];
        }
    }
}
